package com.clwl.supervise.superviseapp.util.bigdata;


import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.clwl.supervise.superviseapp.mapper.base.SysConfigMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 对接大数据相关接口信息
 */
@Component
public class BigDataUtil {


	private static final String TOKEN_USER = "hadoop";

	private static final String TOKEN_CODE = "BML-AUTH";


	public static String devActive;


	public static  String devBertPath ;
	/**
	 * 大数据平台接口总调度
	 * @param id 接口id
	 * @return
	 */
	public static JSONObject dashujuApi(String id,Map<String,String> map) {
		JSONObject dataObj = new JSONObject();
		try {
			//第一步
			Map<String,String> queryMap = queryById(id);
			String path = queryMap.get("path");
			String userToken = queryMap.get("userToken");
			//第二步
			Map<String,String> executeMap = execute(path,userToken,map);
			String status2 = executeMap.get("status");
			if(status2.equals("succeed")) {
				String taskId = executeMap.get("taskId");
				String execId = executeMap.get("execId");

				Thread.sleep(1000);//等待1秒
				//第三步
				String status = getStatus(taskId,execId);
				System.out.println("====get====status==="+status);
				if(status.equals("Succeed")) {
					//第四步
					String resultLocation = getResultLocation(taskId);
					//第五步
					dataObj = getData(taskId,resultLocation);
				}else if(status.equals("Running")){//运行中
					Thread.sleep(1000*5);//等待5秒
					//第三步
					status = getStatus(taskId,execId);
					if(status.equals("Succeed")) {
						//第四步
						String resultLocation = getResultLocation(taskId);
						//第五步
						dataObj = getData(taskId,resultLocation);
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return dataObj;
	}

	/**
	 * 第一步：根据接口id获取token
	 * @param id
	 * @return
	 */
	public static Map<String,String> queryById(String id) {
		String url = "http://42.100.32.58:8088/api/rest_j/v1/dss/apiservice/queryById?id="+id;
		Map<String,String> resultMap = new HashMap<String,String>();
		try {
			String result = HttpUtil.get(url,"",TOKEN_USER,TOKEN_CODE);
			System.out.print("==第一步==queryById==="+result);
			JSONObject jsonObject = JSON.parseObject(result);
			JSONObject jbDate = jsonObject.getJSONObject("data");
			JSONObject jbResult = jbDate.getJSONObject("result");
			String path = jbResult.getString("path");
			String userToken = jbResult.getString("userToken");
			resultMap.put("path", path);
			resultMap.put("userToken", userToken);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 第二步：根据接口url和token获取taskid
	 * @param url
	 * @return
	 */
	public static Map<String,String> execute(String url,String token,Map<String,String> map) {
		String parmasJson = "";
		if(map != null && !map.isEmpty()) {
			for(String key : map.keySet()) {
				parmasJson = ",\""+key+"\": \""+key+"="+map.get(key)+"\"";
			}
		}
		String urlAll = "http://42.100.32.58:8088/api/rest_j/v1/dss/apiservice/execute"+url;
		String jsonStr="{\"moduleName\": \"dss-web\",\"params\": {\"ApiServiceToken\": \""+token+"\""+parmasJson+"}}";
		Map<String,String> resultMap = new HashMap<String,String>();
		try {
			String result = HttpUtil.postGeneralUrl(urlAll, "application/json;charset=UTF-8", jsonStr, "UTF-8",TOKEN_USER,TOKEN_CODE);
			System.out.print("====第二步====execute==="+result);
			JSONObject jsonObject = JSON.parseObject(result);
			String message = jsonObject.getString("message");
			String status = jsonObject.getString("status");
			if(status.equals("0") && message.equals("OK")) {
				JSONObject jbDate = jsonObject.getJSONObject("data");
				String taskId = jbDate.getString("taskId");
				String execId = jbDate.getString("execId");
				resultMap.put("taskId", taskId);
				resultMap.put("execId", execId);
				resultMap.put("status", "succeed");
			}else {
				resultMap.put("status", "failed");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			resultMap.put("status", "failed");
		}
		return resultMap;
	}

	/**
	 * 第三步：获取运行状态
	 * @param taskId
	 * @param execId
	 * @return
	 */
	public static String getStatus(String taskId,String execId) {
		String urlAll = "http://42.100.32.58:8088/api/rest_j/v1/entrance/"+execId+"/status?taskID="+taskId;
		String status = "";
		try {
			String result = HttpUtil.get(urlAll,"",TOKEN_USER,TOKEN_CODE);
			System.out.print("====第三步====getStatus==="+result);
			JSONObject jsonObject = JSON.parseObject(result);
			JSONObject jbDate = jsonObject.getJSONObject("data");
			status = jbDate.getString("status");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return status;
	}

	/**
	 * 第四步：获取ResultLocation
	 * @param taskId
	 * @return
	 */
	public static String getResultLocation(String taskId) {
		String urlAll = "http://42.100.32.58:8088/api/rest_j/v1/dss/apiservice/"+taskId+"/get";
		String resultLocation = "";
		try {
			String result = HttpUtil.get(urlAll,"",TOKEN_USER,TOKEN_CODE);
			System.out.print("====第四步====getResultLocation==="+result);
			JSONObject jsonObject = JSON.parseObject(result);
			JSONObject jbDate = jsonObject.getJSONObject("data");
			JSONObject jbTask = jbDate.getJSONObject("task");
			resultLocation = jbTask.getString("resultLocation").replace("/", "%2F");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultLocation;
	}

	/**
	 * 第五步：获取数据
	 * @param taskId
	 * @param resultLocation
	 * @return
	 */
	public static JSONObject getData(String taskId,String resultLocation) {
		String urlAll = "http://42.100.32.58:8088/api/rest_j/v1/dss/apiservice/openFile?path="+resultLocation+"%2F_1.dolphin&taskId="+taskId;
		String result = "";
//		JSONArray dataArray = new JSONArray();
		JSONObject jbDate = new JSONObject();
		try {
			result = HttpUtil.get(urlAll,"",TOKEN_USER,TOKEN_CODE);
			System.out.println("====第五步====获取数据==="+result);
			JSONObject jsonObject = JSON.parseObject(result);
			jbDate = jsonObject.getJSONObject("data");
//			dataArray = jbDate.getJSONArray("fileContent");
//			for (int i = 0; i < metadataArray.size(); i++) {
//				System.out.println("====get====metadataArray==="+metadataArray.getJSONArray(i));
//				JSONArray dataArray = metadataArray.getJSONArray(i);
//				for(int j = 0; j < dataArray.size(); j++) {
//					System.out.println("====get====dataArray==="+dataArray.getString(j));
//				}
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jbDate;
	}

	/**
	 * 机器学习bert
	 * @param mess
	 * @return
	 */
	public static List<Semantics> bert2Search(String mess) {
		String bertPath = StringUtils.equals(BigDataUtil.devActive, "dev") ? BigDataUtil.devBertPath : StrUtil.blankToDefault(SpringUtil.getBean(SysConfigMapper.class).queryByKey("SYS_CONFIG_BERT_SERVER_PATH").getParamValue(), BigDataUtil.devBertPath);

		//String urlAll = "http://116.130.215.195:8000/ai/Bert2Search";
		String result = "";
		JSONObject jsonObjectParam = new JSONObject();
		JSONObject data = new JSONObject();
		JSONArray ndarray = new JSONArray();
		ndarray.add(mess);
		data.put("ndarray",ndarray);
		jsonObjectParam.put("data",data);
		String jsonStr= StringUtils.equals(BigDataUtil.devActive, "dev") ? "{\"query\": \""+mess+"\"}" : jsonObjectParam.toJSONString();
		List<Semantics> resultList= new ArrayList<>();
		try {
			///System.out.println(BigDataUtil.devBertPath);
			//System.out.println(BigDataUtil.devActive);
			//System.out.println("请求地址:"+bertPath);
			//System.out.println("请求参数:"+jsonStr);
			result = HttpUtil.postGeneralUrl(bertPath, "application/json", jsonStr, "UTF-8",null,null);
			String resultU = HttpUtil.unicodeToString(result);
			JSONObject jsonObject = JSON.parseObject(resultU);

			//System.out.println("====get====result==="+result);
			//System.out.print("====get====resultU==="+resultU);
			JSONArray keysArray;
			if(StringUtils.equals(devActive, "dev")){
				keysArray = jsonObject.getJSONArray("result");
			} else {
				try {
					//出现异常说明返回的消息格式不正确，直接返回空信息
					keysArray = jsonObject.getJSONArray("strData");
				} catch (Exception e) {
					e.printStackTrace();
					keysArray = new JSONArray();
				}
			}
			for (int i = 0; i < keysArray.size(); i++) {
				JSONArray keyValues = JSONObject.parseArray(keysArray.getString(i));
				Semantics  semantics = new Semantics();
				semantics.setValue(keyValues.getString(0));
				semantics.setProbability(keyValues.getString(1));
				semantics.setType("0");
				resultList.add(semantics);
			}
			return resultList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}




	/*  public static void main(String [] args) {

          queryById("7");
          execute("/rcjc","eyJhbGciOiJIUzI1NiJ9.eyJ0b2tlbkRldGFpbCI6eyJhcHBseVVzZXIiOiJoYWRvb3AiLCJhcHBseVRpbWUiOjE2OTIwNzI5MjU3ODcsImFwaVNlcnZpY2VJZCI6NywicHVibGlzaGVyIjoiaGFkb29wIn0sImV4cCI6MTcyMzYwODkyNSwiaWF0IjoxNjkyMDcyOTI1fQ.boENvPzaInsq7fmZeTBWfuvJ-HLVykSg-B6ZPuVg77c");
          getStatus("344","exec_id018019linkis-cg-entrancehadoop6.domain:9104IDE_hadoop_spark_2");
          getResultLocation("344");
          getResultLocation("344","hdfs:%2F%2F%2Ftmp%2Flinkis%2Fhadoop%2Flinkis%2F2023-08-17%2F063853%2FIDE%2F344");
		List<Semantics> resultList = bert2Search("我想要看企业国家抽检报告");
		for (Semantics semantics : resultList) {
			System.out.println(semantics.toString());
		}
    }*/

	/**
	 * 语义实体
	 */
	public static class Semantics {

		/**
		 * 语义分析内容
		 */
		private String value;
		/**
		 * 消息解析类型;0-正常bert流程解析 ；1-使用lengchain chat解析
		 */
		private String type;

		/**
		 * 概率
		 */
		private String probability;


		private List<String> knowledgeBaseList = new ArrayList<>();



		public void setKnowledgeBaseList(List<String> knowledgeBaseList) {
			this.knowledgeBaseList = knowledgeBaseList;
		}



		public List<String> getKnowledgeBaseList() {
			return knowledgeBaseList;
		}


		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public String getProbability() {
			return probability;
		}

		public void setProbability(String probability) {
			this.probability = probability;
		}

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		@Override
		public String toString() {
			return "Semantics{" +
					"value='" + value + '\'' +
					", probability='" + probability + '\'' +
					'}';
		}
	}

	@Value("${spring.profiles.bert_dev_active}")
	public  void setDevActive(String devActive) {
		BigDataUtil.devActive = devActive;
	}
	@Value("${spring.profiles.bertDevPath}")
	public void setDevBertPath(String devBertPath) {
		BigDataUtil.devBertPath = devBertPath;
	}


}

